<template>
  <div class="login">
    <van-nav-bar title="登录"/>
    <!-- 表单结构 -->
    <van-form @submit="login">
  <van-field
    v-model="mobile"
    label="手机号码"
    placeholder="请输入手机号码"
    required
    :rules="rules.mobile"
  />
  <van-field
    v-model="code"
    type="number"
    label="验证码"
    placeholder="请输入验证码"
    required
    :rules="rules.code"
  />
  <div style="margin: 16px;">
    <van-button :disabled='isLoad' :loading='isLoad' loading-text="登录中..."  round block type="info" native-type="submit">提交</van-button>
  </div>
</van-form>
  </div>
</template>

<script>
import { userLogin } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Login',
  data () {
    return {
      isLoad: false, // 是否发送请求
      mobile: '15551450298',
      code: '246810',
      rules: {
        // 手机号校验规则
        mobile: [
          {
            required: true,
            message: '手机号不能为空'
          },
          {
            // 手机号格式
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号码格式不正确'
          }
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.isLoad = true
      try {
        const res = await userLogin(this.mobile, this.code)
        console.log(res.data)
        // this.$store.commit('setToken', res.data)
        this.setToken(res.data)
        this.$toast.success('登录成功')
        // 判断是否需要回退页面，携带参数可以指定回退页面
        const back = this.$route.query.back || '/user'
        // 获取flag的值 ==> 如果有flag，使用back进行回退，不要使用push
        const flag = this.$route.query.flag
        if (flag) {
          return this.$router.back()
        }
        this.$router.push(back)
      } catch (e) {
        this.$toast.fail('登录失败')
        console.log(e)
      }
      // 请求成功还是失败都会执行
      this.isLoad = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
